<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, onMounted, reactive, ref, unref, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import {
  GetAllCoursesApi,
  GetStudentUsersApi,
  GetTeacherUsersApi,
  GetCourseScoreCriteriaApi,
  GetCoursePlanExamScoreApi
} from '@/api/course'
import { Calendar, Stamp, VideoCameraFilled } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Table } from '@/components/Table'
import {
  ElSelect,
  ElOption,
  ElFormItem,
  ElTransfer,
  ElSteps,
  ElStep,
  ElButton,
  ElDivider,
  ElMessage
} from 'element-plus'
const { t } = useI18n()
const { required } = useValidator()
const activeName = ref(1)
const props = defineProps({
  currentRow: {
    type: Object,
    default: () => undefined
  }

  // formSchema: {
  //   type: Array as PropType<FormSchema[]>,
  //   default: () => []
  // }
})
interface selectionType {
  label: string
  value: string
  key?: string
  disabled?: Boolean
}
const plancontent = ref<string>()
const chooes = ref<string[]>([])
const chooesTeachers = ref<string[]>([])
const typeList = ref<selectionType[]>([])
const usersList = ref<selectionType[]>([])
const teacherList = ref<selectionType[]>([])
const GetCourseTypes = async () => {
  const res = await GetAllCoursesApi()
  res.data?.map((item) => {
    typeList.value.push({
      label: item.courseName + '   <' + item.courseTypeName + '>   ',
      value: item.guid,
      key: item.courseName
    })
  })
  const dt = await GetStudentUsersApi()
  let uList: selectionType[] = []
  dt.data?.map((item) => {
    uList.push({
      label: item.depNo + '-' + item.depName + '~' + item.userNo + '-' + item.userName,
      value: item.userNo + '$' + item.userName,
      key: item.userNo + '$' + item.userName + '$' + item.depNo + '$' + item.depName,
      disabled: chooesTeachers.value.includes(
        item.userNo + '$' + item.userName + '$' + item.depNo + '$' + item.depName
      )
    })
  })
  usersList.value = uList
  const tdt = await GetTeacherUsersApi()
  let tList: selectionType[] = []
  tdt.data?.map((item) => {
    tList.push({
      label: item.depNo + '-' + item.depName + '~' + item.userNo + '-' + item.userName,
      value: item.userNo + '$' + item.userName,
      key: item.userNo + '$' + item.userName + '$' + item.depNo + '$' + item.depName,
      disabled: chooes.value.includes(
        item.userNo + '$' + item.userName + '$' + item.depNo + '$' + item.depName
      )
    })
  })
  console.log('tList', tList)
  teacherList.value = tList
  // if (props.currentRow) {
  //   teacherChange(props.currentRow.value.chooesTeachers)
  //   userChange(props.currentRow.value.chooes)
  // }
}
GetCourseTypes()
const courseName = ref('')
const formSchema = ref<FormSchema[]>([
  {
    field: 'courseGuid',
    label: '课程名称',
    component: 'Select',
    componentProps: {
      clearable: true,
      filterable: true,
      placeholder: '请选择课程名称',
      onChange: (value) => {
        console.log('selectChange---------', value)
        if (value) {
          let key = typeList.value.filter((item) => item.value == value)[0].key
          console.log('selectChange-----key----', key)
          courseName.value = key ? key : ''
          getList()
        }
      }
    },
    optionApi: () => {
      return typeList.value
    }
  },
  {
    field: 'planTime',
    label: '考试时间',
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm',
      format: 'YYYY-MM-DD HH:mm',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date',
      DefaultTime: [new Date(), new Date()]
    }
  },
  {
    field: 'resitScore',
    label: '及格线',
    component: 'Input',
    value: 0,
    componentProps: {
      type: 'number',
      placeholder: '请输入及格线'
    }
  },
  {
    field: 'releasePlanCount',
    label: '计划下发数量',
    component: 'Input',
    componentProps: {
      type: 'number',
      placeholder: '请输入下发数量'
    }
  }
  // {
  //   field: 'plancontent',
  //   label: '培训内容',
  //   component: 'Input',
  //   componentProps: {
  //     type: 'textarea',
  //     rows: 3
  //   }
  // }
  // {
  //   field: 'field35',
  //   label: t('formDemo.default'),
  //   component: 'Transfer',
  //   componentProps: {
  //     data: async () => {
  //       const dt = await GetStudentUsersApi()
  //       let uList: selectionType[] = []
  //       dt.data?.map((item) => {
  //         uList.push({
  //           label: item.userNo + '-' + item.userName + '~' + item.depName,
  //           value: item.userNo + '$' + item.userName,
  //           key: item.userNo + '$' + item.userName,
  //           disabled: false
  //         })
  //       })
  //       return uList
  //     }
  //   }
  // }
  // {
  //   field: 'remark',
  //   label: t('common.remark'),
  //   component: 'Input',
  //   componentProps: {
  //     type: 'textarea',
  //     rows: 4
  //   }
  // }
])

const rules = reactive({
  courseGuid: [required()],
  planTime: [required()]
  //  resitScore: [required()],
  // releaseExamDevices: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
interface palnUser {
  UserNo: string
  UserName: string
  DepNo: string
  DepName: string
}
interface scoreCriterion {
  scoreGuid: string
  scoreItem: string
  scoreValue: number
}
const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    let arr: palnUser[] = []
    const formData = await getFormData()
    chooes.value.forEach((item) => {
      let a = item.split('$')
      let obj: palnUser = {
        UserNo: a[0],
        UserName: a[1],
        DepNo: a[2],
        DepName: a[3]
      }
      arr.push(obj)
    })
    let tarr: palnUser[] = []
    chooesTeachers.value.forEach((item) => {
      let a = item.split('$')
      let obj: palnUser = {
        UserNo: a[0],
        UserName: a[1],
        DepNo: a[2],
        DepName: a[3]
      }
      tarr.push(obj)
    })
    formData.teacherUsers = JSON.stringify(tarr)
    formData.planUsers = JSON.stringify(arr)
    formData.examTime = formData.planTime[0] + ' 至 ' + formData.planTime[1]
    formData.plancontent = plancontent.value
    formData.scoreCriterion = []
    let larr: scoreCriterion[] = []
    let sum = 0
    const elTableExpose = await getElTableExpose()
    elTableExpose?.getSelectionRows().map((v) => {
      console.log(v)
      larr.push({
        scoreGuid: v.guid,
        scoreItem: v.scoreItem,
        scoreValue: v.scoreValue
      })
      sum += v.scoreValue
    })

    // if (larr.length == 0) {
    // ElMessage.warning('请选择评分标准')
    // return
    // } else
    if (larr.length > 0) {
      if (formData.resitScore > sum) {
        ElMessage.error('及格线不能大于评分标准总和')
        return
      }
      formData.scoreCriterion = larr
    }
    if (tarr.length == 0) {
      ElMessage.error('请选择老师')
      return
    }
    if (arr.length == 0) {
      ElMessage.error('请选择学员')
      return
    }
    return formData
  }
}
const teacherChange = (e) => {
  usersList.value.map((item) => {
    if (e.includes(item.key)) {
      item.disabled = true
    } else {
      item.disabled = false
    }
  })
}
const userChange = (e) => {
  teacherList.value.map((item) => {
    if (e.includes(item.key)) {
      item.disabled = true
    } else {
      item.disabled = false
    }
  })
}
watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    chooes.value = currentRow.chooes
    chooesTeachers.value = currentRow.chooesTeachers
    plancontent.value = currentRow.planContent
    courseName.value = currentRow.courseName
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
interface itemDt {
  guid: string
}
let isRequest = false
let dtlist: itemDt[] = []
const GetCoursePlanExamScore = async (planGuid) => {
  const elTableExpose = await getElTableExpose()
  if (isRequest || !planGuid) {
    return
    // dtlist.forEach((row, index) => {
    //   let a = elTableExpose?.getSelectionRows().filter((item) => item.scoreGuid == row.scoreGuid)
    //   console.log(elTableExpose?.getSelectionRows())
    //   if (a.length > 0) {
    //     elTableExpose?.toggleRowSelection(dataList.value[index], true)
    //   }
    // })
  } else {
    isRequest = true
    const res = await GetCoursePlanExamScoreApi({ planGuid })

    dtlist.forEach((row, index) => {
      let a = res.data.filter((item) => item.scoreGuid == row.guid)
      if (a.length > 0) {
        elTableExpose?.toggleRowSelection(dataList.value[index], true)
      }
    })
  }
}
const nextSetp = (t) => {
  activeName.value++
}
const preSetp = (t) => {
  activeName.value--
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    // const { pageSize, currentPage } = tableState
    const res = await GetCourseScoreCriteriaApi({
      courseName: courseName.value
    })
    dtlist = res.data || []
    GetCoursePlanExamScore(props.currentRow?.guid)
    return {
      list: res.data || [],
      total: res.data.totalCount || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',

    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),

    table: {
      type: 'index'
    }
  },
  {
    field: 'remark',
    label: '分组',
    sortable: true
  },
  {
    field: 'scoreItem',
    label: '评分分项',
    width: 120,
    sortable: true
  },

  {
    field: 'scoreValue',
    label: '分值',
    width: 80,
    sortable: true
  },
  {
    field: 'scoreContent',
    label: '评分标准',

    sortable: true
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}
</script>

<template>
  <el-steps :active="activeName" simple style="margin-bottom: 20px">
    <el-step title="配置考试信息" :icon="Calendar" @click.enter="activeName = 1" />
    <el-step title="配置人员信息" :icon="Stamp" @click.enter="activeName = 2" />
  </el-steps>
  <div v-show="activeName == 1">
    <Form :rules="rules" @register="formRegister" :schema="formSchema" />
    <el-divider />
    <!-- <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" /> -->
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :height="300"
      emptyText="暂无数据,请添加该课程的评分项"
    />
    <el-divider />
    <div class="btnbox">
      <el-button type="primary" :onClick="nextSetp">下一步</el-button>
    </div>
  </div>
  <div v-show="activeName == 2">
    <el-form-item label="讲师" label-width="88">
      <el-transfer
        v-model="chooesTeachers"
        filterable
        filter-placeholder="输入人员名称或编号"
        :data="teacherList"
        style="width: 100%"
        :titles="['老师列表', '已选老师']"
        @change="teacherChange"
      />
    </el-form-item>
    <el-form-item label="学员" label-width="88">
      <el-transfer
        v-model="chooes"
        filterable
        filter-placeholder="输入人员名称或编号"
        :data="usersList"
        style="width: 100%"
        :titles="['学员列表', '已选学员']"
        @change="userChange"
      />
    </el-form-item>
    <el-divider />
    <div class="btnbox">
      <el-button type="primary" :onClick="preSetp">上一步</el-button>
    </div>
  </div>
</template>
<style scoped>
:deep(.el-transfer-panel) {
  width: 300px !important;
}
:deep(.el-transfer-panel__body) {
  height: 180px !important;
}
.btnbox {
  display: flex;
  justify-content: flex-end;
  margin-top: -10px;
}
:deep(.el-step__title) {
  cursor: pointer;
}
</style>
